<!DOCTYPE HTML>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<meta charset="utf-8">
<head th:include="include :: header">
</head>
<link href="../static/css/selectdate.css" th:href="@{/css/selectdate.css}" rel="stylesheet"/>

<body class="gray-bg">
    <div class="container-div">
		<div class="btn-group hidden-xs" id="toolbar" role="group">
			<!-- <a class="btn btn-outline btn-success btn-rounded" onclick="$.operate.add()" shiro:hasPermission="dailymenu:everydayMenu:add">
				<i class="fa fa-plus"></i> 新增
			</a>
			<a class="btn btn-outline btn-danger btn-rounded" onclick="$.operate.removeAll()" shiro:hasPermission="dailymenu:everydayMenu:remove">
		            <i class="fa fa-trash-o"></i> 删除
		    </a> -->
		    
		     <!-- <a class="left" onclick="decreaseMonth()">123</a>
        	<div><p class="time">{{y}}年{{m+1}}月</p></div>
        	<a  class="right" onclick="addMonth()">456</a> -->
        	
        	<div class="date-content">
		        <a class="left" onclick="x.decreaseMonth()"></a>
		        <div>
		            <p class="time">{{y}}年{{m+1}}月</p>
		        </div>
	        	<a class="right" onclick="x.addMonth()"></a>
	        	
		        <span class="btn-date" onclick="x.getClickDate(0)">全月</span>
		        <span class="btn-date" onclick="x.getClickDate(1)"></span>
		        <span class="btn-date" onclick="x.getClickDate(2)"></span>
		        <span class="btn-date" onclick="x.getClickDate(3)"></span>
		        <span class="btn-date" onclick="x.getClickDate(4)"></span>
		        <span class="btn-date" onclick="x.getClickDate(5)"></span>
		        <span class="btn-date" onclick="x.getClickDate(6)"></span>

		    </div>

			<div class="dropdown">
				<button type="button" class="btn btn-success dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
					排餐导入<span class="caret"></span>
				</button>
				<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
					<li role="presentation">
						<a role="menuitem" href="#"   onclick="x.exportDish(0)" >导入早餐</a>
					</li>
					<li role="presentation">
						<a role="menuitem" href="#" onclick="x.exportDish(1)" >导入午餐</a>
					</li>
					<li role="presentation">
						<a role="menuitem" href="#" onclick="x.exportDish(2)" >导入晚餐</a>
					</li>
					<li role="presentation">
						<a role="menuitem" href="#" onclick="x.exportDish(3)" >导入其他餐</a>
					</li>

				</ul>

			</div>


		</div>

		<div class="col-sm-12 select-table table-striped"> 
			<table id="bootstrap-table" data-mobile-responsive="true"></table>
		</div>
    </div>
    <div th:include="include :: footer"></div>
    <script th:inline="javascript">
        var editFlag = [[${@permission.hasPermi('dailymenu:everydayMenu:edit')}]];
        var removeFlag = [[${@permission.hasPermi('dailymenu:everydayMenu:remove')}]];
        var prefix = ctx + "dailymenu/everyday"
        var open = [[${@dict.getType('daily_is_open')}]];
        
        $(function() {
            var options = {
                url: prefix + "/list",
                createUrl: prefix + "/add",
                updateUrl: prefix + "/edit/{id}",
                removeUrl: prefix + "/remove",
                modalName: "每日菜单",
                search: false,
		        showExport: false,
		        pageSize:30,
                columns: [
				{
					field : 'dailyDate', 
					title : '日期',
					align: 'center',
					width : 160,
					formatter: function(value, row, index) {
						return getDateRule(value);
					}
				},
				{
		            field: 'isBreakFast',
		            title: '早餐',
		            formatter: function(value, row, index) {
			            return '<a href="#" onclick="detail(\'' + row.dailyId + '\',0)">' + getDishNames(value) + '</a>';
			        }
		        },
				{
					field : 'isLunch', 
					title : '午餐',
					formatter: function(value, row, index) {
			            return '<a href="#" onclick="detail(\'' + row.dailyId + '\',1)">' + getDishNames(value) + '</a>';
			        }
				},
				{
					field : 'isDinner', 
					title : '晚餐',
					formatter: function(value, row, index) {
			            return '<a href="#" onclick="detail(\'' + row.dailyId + '\',2)">' + getDishNames(value) + '</a>';
			        }
				},
				{
					field : 'isOther',
					title : '其他餐',
					formatter: function(value, row, index) {
			            return '<a href="#" onclick="detail(\'' + row.dailyId + '\',3)">' + getDishNames(value) + '</a>';
			        }
				},
		        {
		            title: '操作',
		            align: 'center',
		            formatter: function(value, row, index) {
		            	var actions = [];
		            	actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="$.operate.edit(\'' + row.dailyId + '\')">选择常用菜单</a> ');
		            	return actions.join('');
		            }
		        }]
            };
            $.table.init(options);
        });
        
        
        Date.prototype.Format = function (fmt) { //author: meizz 
            var o = {
                "M+": this.getMonth() + 1, //月份 
                "d+": this.getDate(), //日 
                "h+": this.getHours(), //小时 
                "m+": this.getMinutes(), //分 
                "s+": this.getSeconds(), //秒 
                "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
                "S": this.getMilliseconds() //毫秒 
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        }
        
        function getDateRule(value){
        	var date = new Date(value).Format("yyyy-MM-dd");
        	var dateDay = new Date(date).getDay();
        	var week = "";
        	switch (dateDay) {
        	  case 0:week="周日";break
        	  case 1:week="周一";break
        	  case 2:week="周二";break
        	  case 3:week="周三";break
        	  case 4:week="周四";break
        	  case 5:week="周五";break
        	  case 6:week="周六";break
        	 }
        	
        	var newDate = new Date(value).Format("MM-dd");
        	var newDateStr = newDate.split("-");
        	var month = newDateStr[0];
        	var day = newDateStr[1];
        	if(month.substr(0, 1) == "0"){
        		month = month.slice(1);
        	}
        	
        	if(day.substr(0, 1) == "0"){
        		day = day.slice(1);
        	}
        	
        	var show = month+"月"+day+"日";
        	return show+" ( "+week+" )";
        	
        }
        function getDishNames(value){
        	if(value == '0' || value == '1'){
        		return $.table.selectDictLabel(open, value);
        	}else{
        		return value;
        	}
        }
        
        /*菜品-详细*/
		function detail(dailyId,dinnerType) {
        	//alert(dailyId)
        	if(dailyId == "null" || dailyId == null){
        		dailyId = 0;
        	}
			var url = prefix + '/dish/' + dailyId+'/'+dinnerType;
			$.modal.open("选择菜品", url);
		} 
        
        class cdDate {
            constructor() {
                // 报餐列表数据
                this.today = new Date();
                this.y = '';
                this.m = '';
                this.todaystamp = '';
                this.datestampList = [];
                this.selectedDay=[]
            }
            // 月份加减
            addMonth() {
                this.today.setMonth(this.m + 1)
                this.initialize()
                fillhtml()
                //console.log('add')
            }
            decreaseMonth() {
                this.today.setMonth(this.m - 1)
                this.initialize()
                fillhtml()
                //console.log('decrease')
            }
            // 初始化函数：
            initialize() {
                this.y = this.today.getFullYear()
                this.m = this.today.getMonth()
                this.todaystamp =this.today.getTime()
                this.datestampList = []

                let firstStampList = []
                let endStampList = []
                // 按钮还原：
                for(let i of document.querySelectorAll('.btn-date')){
                    i.className  = 'btn-date'
                    i.innerHTML = ''
                }
                document.querySelectorAll('.btn-date')[0].className  += ' actions'
                document.querySelectorAll('.btn-date')[0].innerHTML  = '全月'


                let dayNum = new Date(this.y,this.m+1,0).getDate();  //获取这个月的天数
                let firstday =new Date(this.y,this.m,1)   //获取这个月的第一天
                if(firstday.getDay()!=1){
                        firstStampList.push(firstday)
                }
                for(let i=0;i<dayNum;i++){
                    if(firstday.getDay()==1){
                        firstStampList.push(firstday)
                    }
                    if(firstday.getDay()==0){
                        endStampList.push(firstday)
                    }
                    firstday = new Date(firstday.getTime()+(24*60*60*1000))
                }
                let endday =new Date(this.y,this.m+1,0)   //获取这个月的最后一天
                if(endday.getDay()!=0){
                    endStampList.push(endday)
                }
                //console.log(dayNum,firstStampList,'end',endStampList)
                for(var i=0;i<firstStampList.length;i++){
                    let dateStr0 =firstStampList[i].toLocaleString().split(' ')[0]
                    dateStr0 = dateStr0.replace(/-/g,'/')
                    //console.log(dateStr0)
                    let dateStr1 =endStampList[i].toLocaleString().split(' ')[0]
                    dateStr1 = dateStr1.replace(/-/g,'/')
                    this.datestampList.push([dateStr0,dateStr1])
                    document.querySelectorAll('.btn-date')[i+1].innerHTML = dateStr0.split('/')[1]+'月'+dateStr0.split('/')[2]+'日'+' '+'至'+' '+dateStr1.split('/')[1]+'月'+dateStr1.split('/')[2]+'日'
                }
                //console.log('dayNum',dayNum);
            }
            fill() {
                this.initialize()
                var result = {
                    month: this.m + 1,
                    year: this.y,
                }
                return result
            }

            // 获取点击日期
            getClickDate(index){
                for(let i of document.querySelectorAll('.btn-date')){
                    i.className  = 'btn-date'
                }
                document.querySelectorAll('.btn-date')[index].className  += ' actions'

                if(index==0){
                    //alert(this.y+'/'+(this.m+1))
                    $.table._option.url = prefix + "/listMonth?year="+this.y+"&month="+(this.m+1);
               		$.table.refresh();
                }else{
                    //alert(this.datestampList[index-1])
                    
                    var dateStr = this.datestampList[index-1].toString();
                    //var weekDate = dateStr.split(",");
                    var weekDate = dateStr.split(",");
                    //alert(weekDate[0]+'==='+weekDate[1]);
                    this.selectedDay[0]=weekDate[0];
					this.selectedDay[1]=weekDate[1];
                    $.table._option.url = prefix + "/listWeek?begin="+weekDate[0]+"&end="+weekDate[1];
               		$.table.refresh();

                }
                
            }
            exportDish(index) {
            	if(!this.selectedDay[0] || this.selectedDay[0] == "") {
					$.modal.alert("请选择一个时间段来导入！");
            		return;
				}
				var importUrl = prefix + "/import?begin="+this.selectedDay[0]+"&end="+this.selectedDay[1]+"&index="+index;
				$.modal.open("排餐导入", importUrl,800,560);
				$.table.refresh();

			}
        }

        var x = new cdDate()
        // console.log(x.fill())
        function fillhtml() {
            var add = x.addMonth
            var decrease = x.decreaseMonth
            var de = x.fill()
            var yy = de.year
            var mm = de.month
            //console.log(yy, mm)
            // alert(yy + '-' + mm)
            document.querySelector('.time').innerHTML = yy + '年' + mm + '月';
            $.table._option.url = prefix + "/listMonth?year="+yy+"&month="+mm;
       		$.table.refresh();
        }
        fillhtml();
        
     	// 自适应：
        var offWidth = document.body.clientWidth
       // 设计稿1rem = 100px
       if(offWidth<1214){
           offWidth=1214
       }
       document.getElementsByTagName("html")[0].style.fontSize = offWidth*(100/1920) + 'px'; //把rem的值复制给顶级标签html的font-size

       //console.log('offWidth:'+offWidth);
       window.onresize = function(){
           location=location
       }
 	
    </script>
</body>
</html>